#include "LineStream.h"
#include <stdio.h>
#include <string.h>


LineStream::LineStream(): linesize(0), line(0)
{
}

LineStream::~LineStream()
{
	Clear();
}

void LineStream::Clear()
{
	if (line)
	{
		delete[] line;
		line = 0;
	}
}

bool LineStream::IsLF(char c)
{
	if (c == '\n')
		return true;
	else
		return false;
}

bool LineStream::IsCR(char c)
{
	if (c == '\r')
		return true;
	else
		return false;
}

const char* LineStream::GetLine() const
{
	return line;
}

const char* LineStream::GetNextLine()
{
	char byte;

	Clear();

	while( Peek(&byte, 1) )
	{
		if (IsLF(byte))
		{
			char *lineit;

			lineit = line = new char[linesize+1];
			memset(line, 0, linesize+1);

			linesize++;
			while( linesize )
			{
				Read(&byte, 1);

				if (IsLF(byte))
				{
					linesize--;
				}
				else if (!IsCR(byte))
				{
					*lineit++ = byte;
					linesize--;
				}
			}
			break;
		}
		else if (!IsCR(byte))
		{
			linesize++;
		}
	}

	return line;
}

